package com.campus.merchant.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.campus.common.bean.common.Resp;
import com.campus.merchant.bean.goodsCategory.GoodsCategorySaveBean;
import com.campus.merchant.bean.goodsCategory.GoodsCategoryUpdateBean;
import com.campus.merchant.entity.Goods;
import com.campus.merchant.service.GoodsCategoryService;
import com.campus.merchant.service.GoodsService;
import com.campus.merchant.vo.goodsCategory.GoodsCategoryVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 商品分类表 前端控制器
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-04-18
 */
@RestController
@RequestMapping("/goodsCategory")
public class GoodsCategoryController {
    @Autowired
    private GoodsCategoryService goodsCategoryService;
    @Autowired
    private GoodsService goodsService;

    @ApiOperation("根据商户ID获取商品分类列表")
    @GetMapping("/list")
    public Resp<List<GoodsCategoryVO>> getGoodsCategories(@ApiParam("商户ID") @RequestParam("merchantId") Integer merchantId) {
        List<GoodsCategoryVO> categories = goodsCategoryService.getCategoriesByMerchantId(merchantId);
        return Resp.success(categories);
    }

    @PostMapping("/save")
    public Resp<Integer> saveCategory(@RequestBody @Valid GoodsCategorySaveBean bean) {
        Integer id = goodsCategoryService.saveCategory(bean);
        return Resp.success(id);
    }

    @PostMapping("/update")
    public Resp<Void> updateCategory(@RequestBody @Valid GoodsCategoryUpdateBean bean) {
        goodsCategoryService.updateCategory(bean);
        return Resp.success();
    }

    @ApiOperation("删除商品分类")
    @DeleteMapping("/delete/{id}")
    public Resp<Void> deleteCategory(@ApiParam("分类ID") @PathVariable Integer id) {
        List<Goods> goodsList = goodsService.list(Wrappers.<Goods>lambdaQuery().eq(Goods::getCategoryId, id));
        if(CollectionUtil.isNotEmpty(goodsList)){
            return Resp.error("该分类下存在商品，无法删除");
        }
        goodsCategoryService.deleteCategory(id);
        return Resp.success();
    }
    
    @ApiOperation("根据ID获取商品分类详情")
    @GetMapping("/detail")
    public Resp<GoodsCategoryVO> getCategoryDetail(@ApiParam("分类ID") @RequestParam Integer id) {
        GoodsCategoryVO category = goodsCategoryService.getCategoryDetail(id);
        return Resp.success(category);
    }

}
